﻿using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Generic;

public partial class NPS_app_Marketing_InputActivity : PageBase
{
    #region Event

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BtnAdd.Visible = false;
            lblLimit.Visible = false;
            clearTempAttendant();
            loadFormData();
            if (getMode == FormMode.Editor)
            {
                loadData();
                btnSave.Text = "Update";
            }
        }

    }

    protected void gvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "choose")
        {
            addTempAttendant(Convert.ToInt32(e.CommandArgument.ToString()));
            loadAttendant();
        }
    }

    protected void OnPaging(object sender, GridViewPageEventArgs e)
    {
        gvAttendant.PageIndex = e.NewPageIndex;
        gvAttendant.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        //unvalidated input, please update the validation 11-5-2013
        Entities.NPSMarketingActivity MarketingActivity = new Entities.NPSMarketingActivity()
        {
            iNPSMarketingName = Convert.ToInt16(ddlMarketingName.SelectedValue),
            iNPSMarketingType = Convert.ToInt16(ddlMarketingType.SelectedValue),
            iQuota = 10,
            sxCreator = ICPUser.ID,
            sxDetail = txtDetail.Text,
            sxLocation = txtTempat.Text,
            sxTitle = txtNama.Text,
            dtmStartDate = txtTglMulai.SelectedDate,
            dtmEndDate=txtTglAkhir.SelectedDate
        };

        if (getMode == FormMode.Editor)
        {
            MarketingActivity.sxUpdater = ICPUser.ID;
            MarketingActivity.iID = getItemID;
            updateActivity(MarketingActivity);
        }
        else
        {

            if (saveActivity(MarketingActivity))
            {
                if (getTempAttendant.Count > 0)
                {
                    Controller.NPSMarketingActivityAttendantController maac = new Controller.NPSMarketingActivityAttendantController();
                    int count=0;
                    foreach (int i in getTempAttendant)
                    {
                        Entities.NPSMarketingActivityAttendant attendant = new Entities.NPSMarketingActivityAttendant()
                        {
                            iContactPersonID = i,
                            iNPSMarketingActivityID = result
                        };
                        maac.InsertNPSMarketingActivityAttendantData(attendant);
                    count++;}
                    AlertNotification(count.ToString() + " attendants added");
                }
                AlertNotification(MarketingActivity.sxTitle + " sudah ditambahkan");
                clearForm();
            }
            else
            {
                AlertNotification(MarketingActivity.sxTitle + "gagal ditambahkan");
            }
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        search();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
    }

    protected void gvAttendant_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "deletes")
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());
            deleteTempAttendant(id);
            loadAttendant();
        }
    }
    
    protected void ddlMarketingType_SelectedIndexChanged(object sender, EventArgs e)
    {
        clearTempAttendant();
        if (ddlMarketingType.SelectedIndex == 0)
        {
            BtnAdd.Visible = false;
            lblLimit.Visible = false;
            ddlMarketingName.SelectedIndex = 0;
            ddlMarketingName.Enabled = false;
        }
        else
        {
            //load Activity Name Item
            Controller.NPSMarketingNameController ANController = new Controller.NPSMarketingNameController();
            ddlMarketingName.Items.Clear();
            List<Entities.NPSMarketingName> names = new List<Entities.NPSMarketingName>();
            //names.Add(new Entities.NPSMarketingName() { iID = 0, sxTitle = "Pilih Kegiatan" });
            names.AddRange(ANController.getByMarketingType(Convert.ToInt32(ddlMarketingType.SelectedValue)));
            
            if (names.Count <= 0)
            {
                AlertNotification("Gagal koneksi ke database!");
            }

            ddlMarketingName.DataSource = names;
            ddlMarketingName.DataBind();
            ddlMarketingName.Enabled = true;
        }
    }

    protected void ddlMarketingName_SelectedIndexChanged(object sender, EventArgs e)
    {

        clearTempAttendant();
        if (ddlMarketingName.SelectedIndex == 0)
        {
            BtnAdd.Visible = false;
            lblLimit.Visible = false;
        }
        else
        {
            BtnAdd.Visible = true;
            //loadquota
            getLimit();
            try
            {
                lblLimit.Text = "Max " + Session["currentlimit"].ToString() + " attendants";
                lblLimit.Visible = true;
            }
            catch
            { }
        }
    }
 
    protected void gvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvSearch.PageIndex = e.NewPageIndex;
        pagingload();
        gvSearch.DataBind();
    }

    #endregion

    #region Audy' Custom Function

    protected void getLimit()
    {
        int id = Convert.ToInt32(ddlMarketingName.SelectedValue.ToString());
        if (id != 0)
        {
            Controller.NPSMarketingNameController mnc = new Controller.NPSMarketingNameController();
            Session["currentlimit"] = mnc.getNPSMarketingName(id).iQuota.ToString();
        }
    }
    protected void clearForm()
    {
        clearTempAttendant();
        txtNama.Text = string.Empty;
        ddlMarketingName.SelectedIndex = 0;
        ddlMarketingName.SelectedIndex = 0;
        ddlMarketingName.Enabled = false;
        txtDetail.Text = string.Empty;
        txtTempat.Text = string.Empty;
        txtTglMulai.Clear();
        txtTglAkhir.Clear();
        loadAttendant();
    }

    private void loadSearchForm()
    {
        Controller.NPSCustomerContactController ncc = new Controller.NPSCustomerContactController();
        Session["actSData"] = ncc.NPSCustomerContactList;
        pagingload();
        gvSearch.DataBind();
    }

    private void search()
    {
        Controller.NPSCustomerContactController ncc = new Controller.NPSCustomerContactController();
        Session["actSData"] = ncc.getNPSCustomerContactList(txtSearchName.Text, txtSearchCompany.Text);
        pagingload();
        gvSearch.DataBind();
    }


    protected int QuotaLimit
    {
        get
        {
            try
            {
                return Convert.ToInt32(Session["currentlimit"].ToString());
            }
            catch { return 0; }
        }
    }
    protected void addTempAttendant(int attendantID)
    {
        List<int> attendant = getTempAttendant;
        if (attendant.Count >= QuotaLimit)
        {
            AlertNotification("Your attendant has exceed maximum limit!");
        }
        else
        {
            if (!attendant.Contains(attendantID))
            {
                attendant.Add(attendantID);
                saveAttendant(attendant);
            }
            else
            {
                AlertNotification("Your entered a duplicate Attendant!");
            }
        }
    }

    protected void pagingload()
    {
        gvSearch.DataSource=(List<Entities.NPSCustomerContact>)Session["actSData"];
    }
    protected void saveAttendant(List<int> attendant)
    {
        Session["tAttendantList"] = attendant;
    }

    protected List<int> getTempAttendant
    {
        get
        {
            List<int> attendant;
            try
            {
                attendant = (List<int>)Session["tAttendantList"];
                if (attendant == null)
                {
                    throw new Exception();
                }
            }
            catch { attendant = new List<int>(); }
            return attendant;
        }
    }

    protected void deleteTempAttendant(int index)
    {
        List<int> attendant = getTempAttendant;
        attendant.RemoveAt(index);
        saveAttendant(attendant);
    }
    protected void clearTempAttendant()
    {
        Session["tAttendantList"] = null;
        Session["currentlimit"] = null;
    }

    protected void loadAttendant()
    {
        List<int> data = getTempAttendant;
        List<Entities.NPSCustomerContact> contactPerson = new List<Entities.NPSCustomerContact>();
        Controller.NPSCustomerContactController ncc = new Controller.NPSCustomerContactController();
        foreach (int i in data)
        {
            contactPerson.Add(ncc.getNPSCustomerContact(i, true));
        }
        gvAttendant.DataSource = contactPerson;
        gvAttendant.DataBind();
    }

    protected void loadFormData()
    {
        // load pertama tidak usah load attendant dl
        loadAttendant();
        loadSearchForm();


        //Load Activity Type Item
        Controller.NPSMarketingTypeController ATController = new Controller.NPSMarketingTypeController();
        ddlMarketingType.Items.Clear();
        List<Entities.NPSMarketingType> types = new List<Entities.NPSMarketingType>();
        types.Add(new Entities.NPSMarketingType() { iID = 0, sxTitle = "Pilih Tipe Kegiatan" });
        types.AddRange(ATController.NPSMarketingTypeList);

        if (types.Count <= 1)
        {
            AlertNotification("Gagal koneksi ke database!");
        }

        ddlMarketingType.DataSource = types;
        ddlMarketingType.DataBind();

    }

    protected void loadData()
    {
        //fetch data from DB
        Controller.NPSMarketingActivityController MAController = new Controller.NPSMarketingActivityController();
        Entities.NPSMarketingActivity MarketingActivity = MAController.getNPSMarketingActivity(getItemID, false);

        //set all data to forms
        txtDetail.Text = MarketingActivity.sxDetail;
        txtTempat.Text = MarketingActivity.sxLocation;
        txtTglMulai.Text = string.Format("{0:dd-MM-yyyy}", MarketingActivity.dtmStartDate);
        txtTglAkhir.Text = string.Format("{0:dd-MM-yyyy}", MarketingActivity.dtmEndDate);

        //load Attendant Data
        Controller.NPSMarketingActivityAttendantController MAAController = new Controller.NPSMarketingActivityAttendantController();
        gvAttendant.DataSource = MAAController.getNPSMarketingActivityAttendantList(getItemID);
        gvAttendant.DataBind();
    }

    protected bool saveActivity(Entities.NPSMarketingActivity MarketingActivity)
    {
        Controller.NPSMarketingActivityController MAController = new Controller.NPSMarketingActivityController();
        result = MAController.InsertNPSMarketingActivityData(MarketingActivity);
        if (result == 0)
        { return false; }
        else { return true; }
    }

    public int result = 0;

    protected void updateActivity(Entities.NPSMarketingActivity MarketingActivity)
    {
        Controller.NPSMarketingActivityController MAController = new Controller.NPSMarketingActivityController();
        MAController.UpdateNPSMarketingActivityData(MarketingActivity);
    }
    #endregion

}
